package com.javaweb.newfilter;

import com.javaweb.common.DispatcherTool;
import com.javaweb.common.NullableTool;
import com.javaweb.common.StringTool;
import com.javaweb.newservlelt.LoginServlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "FilterLogin",
            urlPatterns = {"/login"}
)
public class FilterLogin implements Filter {
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req ;
        System.out.println("[INFO] entered freeLoginFilter.") ;
        Cookie [] cookies = request.getCookies() ;
        for (Cookie cookie : cookies) {
            if (LoginServlet.USER_COOKIE.equals(cookie.getName())) {
                 String orginalInfor = cookie.getValue() ;
                System.out.println("[INFO] got a userLoginCookie freeLoginFilter: " + orginalInfor) ;
                String[] tokens = StringTool.decry(orginalInfor) ;
                if (NullableTool.isNull(tokens)) {
                    System.out.println("[INFO] the decrypted tokens was null for free login cookie.") ;
                    DispatcherTool.indirectForwardToClient((HttpServletRequest) req,
                                                            (HttpServletResponse)resp,
                                                         "02/servlet/login.jsp",
                                                          "Cookie解码出错！");
                    return ;
                }
                /*
                forward to loginServlet.
                 */
                req.getRequestDispatcher("login?name=" + tokens[0]
                                                        + "&pwd="
                                                        + tokens[1])
                                          .forward(request, resp);
                return ;

            }
        }

        chain.doFilter(req, resp);
    }
    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
